#!/bin/env python

import logging
import optparse
import sys
import glob
import os

from oriolus.pith.publisher import version
from oriolus.pith.publisher.httppublisher import HttpPublisher

def exit(parser):
    parser.print_help()
    parser.destroy()
    sys.exit(2)
    
def run():
    usage = """usage: httppublish [options] packets"""

    parser = optparse.OptionParser(usage=usage, version = "httppublish %s" % version)
    
    parser.add_option("-d", "--dir", dest = "dir", help = "Directory to scan for packages")

    parser.add_option("-u", "--user", dest = "user_name", help = "User name to access repository")
    parser.add_option("-p", "--pass", dest = "password", help = "Password to access repository")
        
    parser.add_option("-o", "--host", dest = "host", help = "Repository host name")
    parser.add_option("-t", "--path", dest = "path", help = "Path in repository to upload packets to")
    
    (options, args) = parser.parse_args()
    
    logging.basicConfig(level = logging.INFO, format = "[%(levelname)s] %(message)s", )

    if (len(args) == 0) and (options.dir in [None, []]) :
        exit(parser)

    if (not options.host) or (not options.path):
        exit(parser)
   
    user_name = None
    if options.user_name:
        user_name = options.user_name
    password = None
    if options.password:
        password = options.password
        
    publisher = HttpPublisher(options.host, options.path, (user_name, password))
    if options.dir:
        publisher.publish(glob.glob(os.path.join(options.dir, "*.ori")))

    if len(args) > 0: 
        publisher.publish(args)
                
            
if __name__ == "__main__":
    run()
